<!--
 * @Author: dingxiao
 * @Date: 2025-06-19 16:00:23
 * @Description: 安排本周工作计划
-->
<template>
  <div>
    <el-dialog v-if="dialogVisible" class="week-plan-dialog" width="70%" :visible.sync="dialogVisible" title="新增调研工作">
      <jdf-form-dynamic-table
        ref="dynamicTable"
        v-model="list"
        :columns="columns"
        :column-attrs="columnsAttrsAll"
        :is-edit="isEdit"
        :rules="rules"
        lineClamp
        :btnIsTop="true"
        dialog-width="40%"
        :show-btns="showBtns"
        :before-save-fn="beforeSaveFn"
        @selectIdOrOrg="selectIdOrOrg"
      ></jdf-form-dynamic-table>
      <div slot="footer" class="week-plan-dialog-footer">
        <el-button type="primary" size="small" @click="confirm">送牵头部门办理</el-button>
        <el-button size="small" @click="$emit('cancel')">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { message, messageTipConfirm, showErrorMsg } from '@/api/utils/pc-message';
import btnVisibleMixins from '@/mixins/btnVisibleMixins';
import { CAN_EDIT, DEFAULT_DATE_FORMAT, PROVINCE_CODE } from '@/utils/constants';
import ResearchFormService from '@/api/domains/ResearchFormService';
import { getLabel, setFormData } from 'jdf-util';
import {
  cloneDeep, find, isEmpty, map,
} from 'lodash-es';
import { changeDateRangeValue, cleanHtml, joinTypeField } from '@/utils/utils';
import { getStorageInfo } from '@/api/utils/storage-util';
import { htmlNormativeType } from '@/utils/common-form-field';

export default {
  name: 'WeekPlan',
  mixins: [btnVisibleMixins],
  props: {
    // 是否展示弹窗
    visible: Boolean,
    // 表单数据
    formData: {
      type: Object,
      default: () => ({}),
    },
    loginUserInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      service: new ResearchFormService(),
      dialogVisible: false,
      normativeTypeOptions: [],
      selectIndex: 0,
      selectRowKey: '',
      showBtns: ['add', 'del'],
      // 表格列公共属性，为所有列都具备的属性
      columnsAttrsAll: {
        align: 'center',
      },
      // 是否可编辑
      isEdit: true,
      list: [],
      rules: {
        normativeTypes: [{ required: true, message: '连带性规范动作类型不能为空！' }],
        researchDate: [{ required: true, message: '调研日期不能为空！' }],
        researchUnitName: [{ required: true, message: '调研对象不能为空！' }],
        leadingDepartmentName: [{ required: true, message: '牵头部门不能为空！' }],
      },
      columns: [
        {
          label: '',
          type: 'selection',
          width: 55,
          hideInFormItem: true,
        },
        {
          label: '序号',
          type: 'index',
          width: 55,
          hideInFormItem: true,
        },
        {
          label: '连带性规范动作类型',
          prop: 'normativeTypes',
          editable: CAN_EDIT,
          itemType: 'select',
          itemColSpan: 24,
          // 枚举从接口取
          itemOptions: () => this.normativeTypeOptions,
          render: (h, { row: { showNormativeType } }) => htmlNormativeType(h, showNormativeType),
          itemAttrs: {
            placeholder: '请选择类型',
            multiple: true,
            dangerouslyUseHTMLString: true,
          },
          itemEvents: {
            // 选中值发生变化时触发
            change: this.typeChange,
          },
        },
        {
          label: '调研日期',
          prop: 'researchDate',
          editable: CAN_EDIT,
          itemType: 'DatePicker',
          itemColSpan: 24,
          itemAttrs: {
            valueFormat: DEFAULT_DATE_FORMAT,
            rangeSeparator: '至',
            startPlaceholder: '请选择开始日期',
            endPlaceholder: '请选择结束日期',
            type: 'daterange',
            format: DEFAULT_DATE_FORMAT,
          },
          itemEvents: {
            // 用户确认选定的值时触发
            change: this.dateChange,
          },
        },
        {
          label: '调研对象',
          prop: 'researchUnitName',
          editable: CAN_EDIT,
          itemType: 'groupOrg',
          itemColSpan: 24,
          itemAttrs: {
            groupCode: 'DY_COMPANIES_FORM',
            identityId: getStorageInfo('identityId'),
            filterable: true,
            expandAll: true,
            dialogTitle: '选择组织',
          },
          inputAttrs: {
            placeholder: '请选择部门',
            suffixIcon: 'el-icon-office-building',
          },
        },
        {
          label: '牵头部门',
          prop: 'leadingDepartmentName',
          editable: CAN_EDIT,
          itemType: 'groupOrg',
          itemAttrs: {
            // 必传属性
            groupCode: 'DY_SUBMITTER_SUB_DEPT',
            identityId: getStorageInfo('identityId'),
            filterable: true,
            dialogTitle: '选择组织',
            expandLevel: 1,
          },
          inputAttrs: {
            placeholder: '请选择部门',
            suffixIcon: 'el-icon-office-building',
          },
        },
      ],
    };
  },
  created() {
    this.getOptions();
    this.list = cloneDeep(this.formData.workSubjects || []);
  },
  methods: {
    /**
     * 点击确定按钮事件
     */
    confirm() {
      this.dialogVisible = false;
      this.$emit('saveSuccess', this.list);
    },
    /**
     * 日期改变事件
     */
    dateChange(value, data, $set) {
      changeDateRangeValue(value, $set, {
        startField: 'researchStartDate',
        endField: 'researchEndDate',
        rangeDate: 'researchDate',
      });
    },
    /**
     * 打开表格弹窗
     * @param {Number} index 动态表格点击选择按钮行索引
     * @param {String} key 动态表格列key
     */
    openTableDialog(index, key) {
      this.dialogVisible = true;
      this.selectIndex = index;
      this.selectRowKey = key;
    },
    /**
     * 表单数据保存前的回调函数
     */
    beforeSaveFn(data) {
      const { loginName } = this.loginUserInfo;
      const { researchUnitNameIds, leadingDepartmentNameIds } = data;
      setFormData({
        set: this.$set,
        formData: data,
        data: {
          leadingUserId: loginName,
          leadingUserName: getStorageInfo('userName'),
          researchUnitCode: researchUnitNameIds,
          leadingDepartmentId: leadingDepartmentNameIds,
        },
        fieldObj: {
          leadingUserId: 'leadingUserId',
          leadingUserName: 'leadingUserName',
          researchUnitCode: 'researchUnitCode',
          leadingDepartmentId: 'leadingDepartmentId',
        },
      });
    },
    /**
     * 连带性规范动作类型变化事件
     */
    typeChange(value, data, $set) {
      joinTypeField(this.normativeTypeOptions, value, $set);
    },
    /**
     * 选人/组织确定事件
     */
    selectIdOrOrg({ clickField, datas, formData }) {
      // TODO: 根据点击的字段进行不同的处理
    },
    /**
     * 获取调研类型枚举
     */
    async getOptions() {
      try {
        const data = await this.service.getTenantList();
        this.normativeTypeOptions = data.map(({ specificRequirement, id }) => ({
          label: specificRequirement,
          value: id,
        }));
      } catch (error) {
        showErrorMsg(error);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .week-plan-dialog {
  .jdf-form-dynamic-table {
    display: flex;
    flex-direction: column-reverse;
  }
  .week-plan-dialog-footer {
    text-align: center;
  }
}
</style>
